package com.liukang.search.itemIndex;

import com.alibaba.fastjson.JSON;
import com.liukang.common.client.ItemClient;
import com.liukang.common.dto.Item;
import com.liukang.common.dto.PageDTO;
import com.liukang.search.pojo.ItemDoc;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.List;

@SpringBootTest
public class ItemDocument {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private RestHighLevelClient client;

    @Test
    void testItemDocument() throws IOException {
        int page = 1;
        while (true){
            PageDTO<Item> pageDTO = itemClient.itemList(page, 200);
            List<Item> lists = pageDTO.getList();
            BulkRequest request = new BulkRequest();
            if (lists.size() <= 0){
                break;
            }
            for (Item list : lists) {
                ItemDoc itemDoc = new ItemDoc(list);
                request.add(new IndexRequest("item")
                        .id(itemDoc.getId().toString())
                        .source(JSON.toJSONString(itemDoc), XContentType.JSON));
            }
            client.bulk(request, RequestOptions.DEFAULT);
            page++;
        }
    }
}
